{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## decoding demo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/derek/anaconda3/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n",
      "  return f(*args, **kwds)\n",
      "/home/derek/anaconda3/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n",
      "  return f(*args, **kwds)\n",
      "/home/derek/anaconda3/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n",
      "  return f(*args, **kwds)\n"
     ]
    }
   ],
   "source": [
    "from collections import Counter\n",
    "from preprocessing import CharacterIndexer, SlotIndexer, IntentIndexer\n",
    "from gensim.models import Word2Vec\n",
    "import json\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import pickle\n",
    "import h5py\n",
    "import math"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "we can load the layers from the `json` file so we only need the loading functions and the custom layers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n",
      "/home/derek/anaconda3/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n",
      "  return f(*args, **kwds)\n"
     ]
    }
   ],
   "source": [
    "from keras_contrib.layers import CRF\n",
    "from keras_contrib.utils import save_load_utils\n",
    "from kutilities.layers import AttentionWithContext\n",
    "from keras.models import model_from_json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "sentindexer = pickle.load(open('encoded/atis_sentindexer.pkl', 'rb'))\n",
    "slotindexer = pickle.load(open('encoded/atis_slotindexer.pkl', 'rb'))\n",
    "intindexer  = pickle.load(open('encoded/atis_intindexer.pkl',  'rb'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## model loading\n",
    "\n",
    "due to the `keras-contrib` CRF and added attention layers, the easiest way to load the model is to recreate it and load the weights."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "modelname = 'test_model'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import keras\n",
    "with open('model/'+modelname+'.json') as f:\n",
    "    json_string = f.read()\n",
    "    \n",
    "model = model_from_json(json_string, custom_objects={\"CRF\": CRF, \"AttentionWithContext\" : AttentionWithContext})\n",
    "\n",
    "model.load_weights('model/'+modelname+'.h5')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### test loaded model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "tst_text_idx = np.load('encoded/tst_text_idx.npy')\n",
    "tst_char_idx = np.load('encoded/tst_char_idx.npy')\n",
    "tst_slot_idx = np.load('encoded/tst_slot_idx.npy')\n",
    "tst_int_idx  = np.load('encoded/tst_int_idx.npy')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "prd_slots_dist, prd_ints_dist = model.predict([tst_text_idx, tst_char_idx])\n",
    "prd_int_idx  = np.squeeze(np.argmax(prd_ints_dist, axis=-1))\n",
    "prd_slot_idx = np.argmax(prd_slots_dist, axis=-1)\n",
    "prd_ints = intindexer.inverse_transform(prd_int_idx)\n",
    "tru_ints = intindexer.inverse_transform(tst_int_idx)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INTENT ACC:   0.9630459126539753\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/derek/anaconda3/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n",
      "  return f(*args, **kwds)\n",
      "/home/derek/anaconda3/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n",
      "  return f(*args, **kwds)\n"
     ]
    }
   ],
   "source": [
    "from sklearn.metrics import accuracy_score\n",
    "print('INTENT ACC:  ', accuracy_score(tru_ints, prd_ints))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### decoding functions\n",
    "\n",
    "format the input string properly (lower-case, add BOS and EOS tags, strip punctuation, and index), predict on the model, use `argmax` to get predictions then `inverse_transform()` back into human-readable labels\n",
    "\n",
    "a more convenient way to do this would be to encapsulate all the above and below into a class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "def preprocess(snt):\n",
    "    snt = snt.lower()\n",
    "    snt = re.sub(r'[^0-9a-z\\s]', '', snt)\n",
    "    snt = snt.split()\n",
    "    snt = ['BOS'] + snt + ['EOS']\n",
    "    snt = [snt]\n",
    "    out = sentindexer.transform(snt)\n",
    "    return snt, out[0], out[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def predict(s):\n",
    "    tk, wt, ct = preprocess(s)\n",
    "    tk = tk[0]\n",
    "    sp, ip = model.predict([wt, ct])\n",
    "    sp = np.argmax(sp, axis=-1)\n",
    "    ip = np.argmax(ip, axis=-1)\n",
    "    sp = slotindexer.inverse_transform(np.expand_dims(sp, axis=-1))[0]\n",
    "    sp = [x.split('-')[-1] for x in sp]\n",
    "    \n",
    "    spd = {}\n",
    "    for i, p in enumerate(sp):\n",
    "        if p != 'O':\n",
    "            if p in spd.keys():\n",
    "                spd[p].append(tk[i])\n",
    "            else:\n",
    "                spd[p] = []\n",
    "                spd[p].append(tk[i])\n",
    "    \n",
    "    spo = {}\n",
    "    for k in spd.keys():\n",
    "        spo[k] = ' '.join(spd[k])\n",
    "    \n",
    "    ip = intindexer.inverse_transform([ip]+[[0]])[0]\n",
    "\n",
    "    print('query:', s)\n",
    "    print('slots:')\n",
    "    print(spo)\n",
    "    print('intent:', ip)\n",
    "    \n",
    "    return spo, ip\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "query: looking for direct flights from Chicago to LAX\n",
      "slots:\n",
      "{'connect': 'direct', 'fromloc.city_name': 'chicago', 'toloc.city_name': 'lax'}\n",
      "intent: atis_flight\n"
     ]
    }
   ],
   "source": [
    "inpt = \"looking for direct flights from Chicago to LAX\"\n",
    "a, b = predict(inpt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "query: give me flights and fares from New York to Dallas\n",
      "slots:\n",
      "{'fromloc.city_name': 'new york', 'toloc.city_name': 'dallas'}\n",
      "intent: atis_flight#atis_airfare\n"
     ]
    }
   ],
   "source": [
    "inpt = \"give me flights and fares from New York to Dallas\"\n",
    "a, b = predict(inpt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "query: i want a first class flight to los angeles\n",
      "slots:\n",
      "{'class_type': 'first class', 'toloc.city_name': 'los angeles'}\n",
      "intent: atis_flight\n"
     ]
    }
   ],
   "source": [
    "inpt = \"i want a first class flight to los angeles\"\n",
    "a, b = predict(inpt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "base"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
